<template>
  <div class="chart-top">
    <el-switch
      v-show="showTypeSwitch"
      v-model="showType"
      active-text="single"
      inactive-text="accumulated"
    />

    <el-switch
      v-show="rateSwitch"
      v-model="isRate"
      active-text="rate"
      inactive-text="normal"
    />

    <el-button
      v-show="deleteButen"
      class="filter-item"
      type="primary"
      icon="el-icon-delete"
      @click="del()">
    </el-button>

    <div :class="className" :style="{ height: height, width: width }" ref="chart"/>
  </div>
</template>

<script>
import * as echarts from 'echarts'

require('echarts/theme/macarons') // echarts theme
import resize from '@/utils/resize'

export default {
  mixins: [resize],
  props: {
    className: { type: String, default: 'chart' },
    index: { type: Number, default: 0 },
    keyid: { type: Number, default: 0 },
    width: { type: String, default: '100%' },
    height: { type: String, default: '350px' },
    autoResize: { type: Boolean, default: true },
    chartData: { type: Object, required: true },
    deleteButen: { type: Boolean, default: false },
    rateSwitch: { type: Boolean, default: true },
    showTypeSwitch: { type: Boolean, default: true },
    // showType: { type: Boolean, default: false },
    title: { type: String, default: '' },
    y2List: { type: Array, default: () => [] },
    rataDiviAry: { type: Array, default: () => [] }
  },
  data() {
    return {
      chart: null,
      showChartData: {},
      curStart: 0,
      curPreStart: 0,
      curEnd: 100,
      dailyChartType2: true,
      isRate: false,
      showType: true,
      charTitle: '统计图'
    }
  },
  watch: {
    chartData: {
      deep: true,
      handler() {
        this.setOptions()
      }
    },
    showType: {
      deep: true,
      handler() {
        this.updateOptions()
      }
    },
    isRate: {
      deep: true,
      handler() {
        this.updateOptions()
      }

    }
  },
  mounted() {
    this.$nextTick(() => {
      this.initChart()
    })
  },
  beforeDestroy() {
    if (!this.chart) {
      return
    }
    this.chart.dispose()
    this.chart = null
  },
  methods: {
    del() {
      this.$emit('del', this.keyid)
    },
    initChart() {
      // console.log('initChart')
      // console.log(this.chartData)
      this.chart = echarts.init(this.$refs.chart, 'macarons')
      // this.setOptions(this.chartData)
      // this.chart.on('click', (param) => {
      //   console.log(param)
      //   this.$emit('dayChartClick', param)
      // })
      this.chart.on('datazoom', (param) => {
        // console.log(' start end change')
        this.curStart = param.start
        this.curEnd = param.end
        // console.log(param)
        // console.log(this.chart.getOption().dataZoom[0].startValue)
        if (!this.showType) {
          const length = this.showChartData.length
          if (length !== undefined && length > 0) {
            this.updateOptions()
          }
        }
      })
      this.setOptions()
    },
    choseYAxisIndex(data) {
      // // console.log(data)
      // // console.log(this.y2List)
      if (this.y2List.indexOf(data) >= 0) {
        return 1
      } else {
        return 0
      }
    },
    getData(arr) {
      var arr2 = []
      if (this.isRate) {
        for (let i = 0; i < arr.length; i++) {
          try {
            if (this.rataDiviAry[i] !== 0) {
              arr2.push(arr[i] / this.rataDiviAry[i])
            } else {
              arr2.push(arr[i])
            }
          } catch (exception) {
            arr2.push(arr[i])
          }
        }
        // console.log(arr)
        // console.log(this.rataDiviAry)
        // console.log(arr2)
        return arr2
      }
      return arr
    },
    setOptions() {
      // console.log('setOptions')
      this.showChartData = JSON.parse(JSON.stringify(this.chartData))
      if (this.showChartData.x_axis === undefined) return
      const y_keys = this.showChartData.ys_axis.map((v) => v.name)
      const chart_series = this.showChartData.ys_axis.map((v) => {
        return {
          name: v.name,
          smooth: true,
          type: 'line',
          yAxisIndex: this.choseYAxisIndex(v.name), // 对应的坐标  0 左侧y轴 1 右侧y轴
          data: this.getData(v.data)
        }
      })

      if (this.title !== null && this.title !== '') {
        this.charTitle = this.title
      }
      // console.log('chart_series')
      this.chart.setOption({
        // title: { left: 'left', text: this.title },

        title: {
          text: this.charTitle,
          x: 'center',
          y: '1px',
          textStyle: {
            color: '#3A7BD5',
            fontSize: 14
          },
          textAlign: 'left'
        },
        grid: { left: '2%', right: '2%', bottom: '3%', containLabel: true },
        tooltip: {
          trigger: 'axis',
          axisPointer: { type: 'cross' },
          padding: [5, 10]
        },
        xAxis: { data: this.showChartData.x_axis.data },
        yAxis: [{
          axisTick: { show: false }, axisLabel: {
            formatter: function(value, index) {
              if (Math.abs(value) >= 100000000) {
                return value / 100000000 + '亿'
              } else if (Math.abs(value) >= 10000) {
                return value / 10000 + '万'
              } else {
                return value
              }
            }
          }, scale: true
        }, {
          type: 'value', axisLabel: {
            formatter: function(value, index) {
              if (Math.abs(value) >= 100000000) {
                return value / 100000000 + '亿'
              } else if (Math.abs(value) >= 10000) {
                return value / 10000 + '万'
              } else {
                return value
              }
            }
          }, scale: true
        }],
        legend: { left: 'right', data: y_keys, top: '17px' },
        series: chart_series,
        dataZoom: [
          { show: true, realtime: true, start: 0, end: 50, zoomOnMouseWheel: false },
          { type: 'inside', filterMode: 'empty' }
        ]
      })
      this.chart.dispatchAction({ type: 'dataZoom', start: 0, end: 100 })
    },

    updateOptions() {
      // const len = this.showChartData.length
      // var i = 0
      // 从小往大拖
      // if (this.curPreStart < this.curStart) {
      //   i = Math.floor((this.curStart / 100) * len - 0.2)
      // } else {
      //   // 从大往小拖
      //   i = Math.floor((this.curStart / 100) * len + 0.2)
      // }
      // 这里不能通过自己的计算， 推测 echart存在弹性变更 startValue 和 endValue
      const i = this.chart.getOption().dataZoom[0].startValue
      const j = this.chart.getOption().dataZoom[0].endValue + 1
      // console.log('i', i, this.curStart)
      // console.log('j', j, this.curEnd)
      this.showChartData = JSON.parse(JSON.stringify(this.chartData))
      // console.log('updateOptions')
      var chart_series = {}
      if (this.showType) {
        chart_series = this.showChartData.ys_axis.map((v) => {
          return {
            name: v.name,
            smooth: true,
            type: 'line',
            data: this.getData(v.data)
          }
        })
      } else {
        const accumulator = (arr) =>
          arr.map(
            (
              (sum) => (value) =>
                (sum += value)
            )(0)
          )
        chart_series = this.showChartData.ys_axis.map((v) => {
          return {
            name: v.name,
            smooth: true,
            type: 'line',
            data: accumulator(this.getData(v.data))
          }
        })
        if (i > 0) {
          for (let k = 0; k < chart_series.length; k++) {
            const num = chart_series[k].data[i - 1]
            for (let m = i; m < j; m++) {
              chart_series[k].data[m] = chart_series[k].data[m] - num
            }
          }
        }
      }

      const op = {
        xAxis: { data: this.showChartData.x_axis.data },
        series: chart_series,
        dataZoom: [
          {
            show: true,
            realtime: true,
            start: this.curStart,
            end: this.curEnd,
            zoomOnMouseWheel: false
          },
          {
            type: 'inside', filterMode: 'empty', rangeMode: ['value', 'value']
          }
        ]
      }
      // console.log(op)
      this.chart.setOption(op)
      // this.chart.dispatchAction({ type: 'dataZoom', start: 0, end: 100 })
    }
  }
}
</script>
<style>
.el-switch {
  margin-right: 15px;
}

.chart-top {
  margin-top: 5px;
}

</style>
